package main

import (
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/data/binding"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/os/gfile"
	"github.com/gogf/gf/v2/text/gstr"
	"github.com/gogf/gf/v2/util/gconv"
	"github.com/y2h/fyne_poem/dbb"
	"github.com/y2h/fyne_poem/menu"
	"github.com/y2h/fyne_poem/util"
	"github.com/y2h/fyne_poem/widgets"
)

func connect() {
	pth, _ := dbpath.Get()
	dbbase := gfile.Name(pth)
	newDb, _ = gdb.New(gdb.ConfigNode{
		Type: "sqlite",
		Name: pth,
	})
	tbls, _ = newDb.Tables(newDb.GetCtx())
	menu.Glog.Info(newDb.GetCtx(), "tables of ", dbbase, " :", tbls)
	db, _ = newDb.Master()
	tblList.Set(tbls)
	for _, tbl := range tbls {
		//util.Data[tbls[i]] = GetCols(db, tbls[i], msg)
		//util.Data[tbls[i]] = strings.Split(gstr.Replace(newDb.Model(tbls[i]).GetFieldsStr(), "`", ""), ",")
		//util.Data[tbls[i]] = strings.Split(newDb.Model(tbls[i]).GetFieldsStr(), ",")
		// _, util.Data[tbl] = dbb.SqliteTblColsGF(newDb, tbl)
		_, cols := dbb.SqliteTblColsGF(newDb, tbl)
		kcols := tbl + "/" + "字段(" + gconv.String(len(cols)) + ")"
		util.Data[tbl] = []string{kcols,
			dbbase + "/" + tbl + "/Indexes", dbbase + "/" + tbl + "/触发器"}
		gstr.PrefixArray(cols, tbl+"/")
		util.Data[kcols] = cols
		// for i, col := range cols {
		// util.Data[tbl][i] = util.TblCol(tbl, col)
		// util.Data[kcols][i] = util.TblCol(tbl, col)
		// }
	}

	widgets.KiRoot()
	widgets.SetKi(newDb, dbbase)
	tabs.Append(container.NewTabItem("dbtree",
		widgets.Dbtree(newDb, msg, w, a)))
	util.Data[""] = []string{dbbase}

	ktbls := "Tables(" + gconv.String(len(tbls)) + ")"
	util.Data[dbbase] = []string{ktbls}
	util.Data[ktbls] = tbls
	// widgets.Treee.OpenAllBranches()
	widgets.Treee.OpenBranch(ktbls)

	widgets.CtnData = container.NewHBox()
	widgets.Bdcols = binding.NewStringList()
	widgets.Bdcols.AddListener(binding.NewDataListener(func() {
		widgets.Treee.Refresh()
		widgets.CtnData.Refresh()
	}))
}
